package com.ssms.common.Interceptor;

import com.ssms.common.AnnotationUtils.Authentication;
import com.ssms.common.AnnotationUtils.NotNull;
import com.ssms.exception.AuthenticationException;
import com.ssms.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    @NotNull
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        //验证token
        if(!JwtUtils.verifyToken(token)) {
            throw new AuthenticationException("登录信息过期");
        }
        //获取身份
        String realRole = JwtUtils.getClaims(token).get("role").toString();

        HandlerMethod handlerMethod = (HandlerMethod)handler;

        //在访问的方法上寻找注解
        Authentication permission = handlerMethod.getMethodAnnotation(Authentication.class);
        //若为null则在访问的方法所属的类上寻找注解
        if(permission == null) {
            permission = ((HandlerMethod) handler).getBeanType().getAnnotation(Authentication.class);
        }

        //若上述的都为空，则直接放行
        if(permission == null) {
            return true;
        }

        String[] role = permission.value();
        for (String s:role) {
            if(s.equals(realRole)){
                return true;
            }
        }
        throw new AuthenticationException("暂无权限");
    }
}
